<?php

namespace EchoPHP\Loader;

use Exception;

class Loader {

    private static $loader;
    private static $rootPath;

    /**
     * 运行自动加载，定义项目类库默认路径等
     * @param string $rootPath
     * @return mixed
     * @throws Exception
     */
    public static function getLoader($rootPath = '') {
        if (!is_null(self::$loader)) {
            return self::$loader;
        }
        //定义项目根目录
        if (!empty($rootPath)) {
            self::$rootPath = $rootPath;
        } else {
            self::$rootPath = self::getRootPath();
        }

        self::$loader = $loader = self::getComposerLoader();
        //注册命名空间
        $namespaces = [
            'EchoPHP\\' => self::$rootPath . '/Library',
            'app\\' => self::$rootPath . '/app',
        ];
        foreach ($namespaces as $namespace => $path) {
            $loader->addPsr4($namespace, $path, true);
        }
        //添加自动加载第三方类库目录
        $loader->addPsr4('', self::$rootPath . '/extend');
    }

    /**
     * 获取composer自动安装的类库自动加载方法
     * @return mixed
     * @throws Exception
     */
    protected static function getComposerLoader() {
        if (!is_file(self::$rootPath . '/vendor/autoload.php')) {
            throw new Exception('composer类库尚未安装');
        }
        return (require self::$rootPath . '/vendor/autoload.php');
    }


    /**
     * 获取项目根目录路径
     * @return string
     */
    protected static function getRootPath() {
        $rootPath = dirname(dirname(__DIR__));
        return $rootPath;
    }
}